const config = require('../../config.js')

Page({
  data: {
    cartNum:0,
    currentTab: 0,
    swiperHeight: "",
  },
  onLoad: function (options) {
    var userInfo = getApp().globalData.userInfo;

   
    this.initCart();
    var that =this;
    var goodsId = options.productId;
    wx.request({
      url: config.requestUrl +'/goods/findById',
      data: { "id": goodsId },
      header: {
        'token': userInfo.xOpenid // 默认值
      },
      success(res) {
        that.setData({ "goods": res.data });
      }
    });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          swiperHeight: res.windowHeight + 20
        });
      }
    })
  },

  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换
  clickTab: function (e) {
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },

  joinCart:function(e){
    var userInfo = getApp().globalData.userInfo;
    var that = this;
    var goodsId = e.currentTarget.dataset.id;
    wx.request({
      url: config.requestUrl +'/order/addCart',
      data:{"goodsId":goodsId},
      header: {
        'token': userInfo.xOpenid // 默认值
      },
      success(res) {
        that.initCart();
      }
    });
  },
  initCart:function(){
    var userInfo = getApp().globalData.userInfo;
    var that = this;
    wx.request({
      url: config.requestUrl +'/order/getCartInfo',
      header: {
        'token': userInfo.xOpenid // 默认值
      },
      success(res) {
        
        if (res.data.data.length!=0){
          var cartNum = 0;
          for (var i = 0; i < res.data.data.length;i++){
            var cartInfo = res.data.data[i];
              cartNum = cartInfo.amount+cartNum;
          }
          that.setData({"cartNum":cartNum});
        }
      }
    });
  },
  goShop:function(){
    wx.switchTab({
      url: "/pages/shopCart/shopCart"
    })
  },
  goBuy:function(){
    wx.navigateTo({
      url: '/pages/order/order',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})